package com.mata.worktime.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mata.worktime.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.mata.worktime.entity.user.Dept;
import com.mata.worktime.entity.user.TreeNode;
import com.mata.worktime.entity.user.User;
import com.mata.worktime.entity.work.Project;
import com.mata.worktime.enums.ResultEnum;
import com.mata.worktime.exception.BaseException;
import com.mata.worktime.service.user.DeptService;

import java.util.*;

import static com.mata.worktime.util.security.ShiroUtils.getLoginName;


/**
 * 部门信息- 获取相关部门
 *
 * @author 占超群
 */
@Controller
@RequestMapping("/system/dept")
public class DeptController
{

    @Autowired
    private DeptService deptService;

    /**
     * 部门管理
     *
     * @return 部门管理页
     */
    @RequiresPermissions("system:dept:view")
    @GetMapping("/view")
    public String dept()
    {
        return "dept/dept";
    }

    /**
     * 获得父级dept（中心)
     *
     * @return 父级部门列表
     */
    @RequestMapping("/getParentDept")
    @ResponseBody
    public List<Dept> getParentDept()
    {
        return deptService.getParentDept();
    }

    /**
     * 获取孩子部门(组)
     *
     * @param parentId 父部门id
     * @return 子部门列表
     */
    @RequestMapping("/getChildrenDept")
    @ResponseBody
    public List<Dept> getChildrenDept(Long parentId)
    {
        return deptService.getChildrenDept(parentId.toString());
    }

    /**
     * 条件获得所有部门
     *
     * @param deptName 部门名
     * @return 部门列表
     */
    @RequiresPermissions("system:dept:list")
    @RequestMapping("/getAll")
    @ResponseBody
    public List<Dept> getAllDept(String deptName)
    {
        return deptService.list(new QueryWrapper<Dept>()
            .like(StringUtils.isNotBlank(deptName), "dept_name", deptName));
    }

    /**
     * 增加部门
     *
     * @param dept 部门信息
     * @return 统一结果
     */
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public ResultVO add(Dept dept)
    {
        dept.setUpdateBy(getLoginName());
        dept.setUpdateTime(new Date());
        dept.setCreateBy(getLoginName());
        dept.setCreateTime(new Date());
        String ancestors = getAncestors(dept.getParentId());
        dept.setAncestors(ancestors);
        dept.setStatus("0");
        dept.setDelFlag("0");
        return ResultVO.success(deptService.save(dept));
    }

    /**
     * 删除指定id的部门
     *
     * @param deptId 部门id
     * @return 统一结果
     */
    @RequiresPermissions("system:dept:remove")
    @DeleteMapping("/del/{deptId}")
    @ResponseBody
    public ResultVO del(@PathVariable("deptId") Long deptId)
    {
        List<User> userList = deptService.checkIfExistUser(deptId.toString());
        if (null != userList && userList.size() > 0)
        {
            throw new BaseException(ResultEnum.DEPT_EXSIT_USERS);
        }

        return ResultVO.success(deptService.removeById(deptId));
    }

    /**
     * 选择部门树
     *
     * @param deptId 部门id
     * @param mmap   模型
     * @return 部门树页面
     */
    @GetMapping("/selectDeptTree/{deptId}")
    public String selectDeptTree(@PathVariable("deptId") Long deptId, Model mmap)
    {
        mmap.addAttribute("dept", deptService.selectDeptById(deptId));
        return "dept/tree";
    }

    /**
     * 加载部门列表树
     *
     * @return 部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Map<String, Object>> treeData(Project project, User user)
    {
        return deptService.selectDeptTree(project, user);
    }

    /**
     * 加载部门select树
     *
     * @return 部门列表树
     */
    @GetMapping("/treeDataSelect")
    @ResponseBody
    public List<TreeNode> treeDataSelect(Project project, User user)
    {
        List<TreeNode> result=new ArrayList<>();
        List<Map<String, Object>> list = deptService.selectDeptTree(project, user);
        TreeNode rootNode = new TreeNode();
        List<TreeNode> allDept = new ArrayList<>();
        for (int i = 0; i < list.size(); i++)
        {
            if (("0").equals(list.get(i).get("pId")))
            {
                rootNode.setId(list.get(i).get("id").toString());
                rootNode.setText(list.get(i).get("name").toString());
            }
            TreeNode node = new TreeNode();
            node.setId(list.get(i).get("id").toString());
            node.setText(list.get(i).get("name").toString());
            node.setpId(list.get(i).get("pId").toString());
            allDept.add(node);

          List<Dept> depts=deptService.list(new QueryWrapper<Dept>()
              .like("parent_id", node.getId()));


        }
        buildTree(rootNode,allDept);
        result.add(rootNode);
        return result;
    }

    /**
     * 构建树
     *
     * @param node
     * @param nodes
     */
    private void buildTree(TreeNode node, List<TreeNode> nodes)
    {
        if(node.getChildren()!=null){
            node.setChildren(new ArrayList<>());
            for (TreeNode n : nodes)
            {

                if (StringUtils.isNotEmpty(n.getpId()) && n.getpId().equals(node.getId()))
                {
                    node.getChildren().add(n);
                }
            }
            for (TreeNode n : node.getChildren())
            {
                buildTree(n, nodes);

            }
        }



    }

    /**
     * 跳转更新页面
     *
     * @param deptId 部门id
     * @param model  模型
     * @return 更新页
     */
    @GetMapping("/update/{deptId}")
    public String updatePage(@PathVariable("deptId") Long deptId, Model model)
    {
        Dept dept = deptService.getById(deptId);
//        Dept parentDept = deptService.getById(dept.getParentId());
        model.addAttribute("dept", dept);
//        model.addAttribute("parentDept", parentDept);
        return "dept/update";
    }

    /**
     * 修改部门
     *
     * @param deptId 部门id
     * @param dept   部门信息
     * @return 统一结果
     */
    @RequiresPermissions("system:dept:edit")
    @PutMapping("/update/{deptId}")
    @ResponseBody
    public ResultVO update(@PathVariable("deptId") Long deptId, Dept dept)
    {
        dept.setId(deptId);
        return ResultVO.success(deptService.updateById(dept));
    }

    /**
     * 获取祖先id 字符串
     *
     * @param parentId 父id
     * @return 祖先id的字符串
     */
    public String getAncestors(Long parentId)
    {
        //获取父部门
        Dept parentDept = deptService.getById(parentId);
        //获取父部门的祖级列表
        String parentAncestors = parentDept.getAncestors();
        //拼接
        return parentAncestors + "," + String.valueOf(parentId);
    }

}
